// var propererList = [
//     {"name": "颜色", p_enums: ['白色', '黑色']},
//     {"name": "尺寸", p_enums: ['S', 'M']},
//     {"name": "重量", p_enums: ['轻', '重']},
// ];


function testProduct(propererList) {


    var y = 1;
    for (var i = 0; i < propererList.length; i++) {
        y = y * propererList[i].p_enums.length;
    }


    var array = [];
    for (var i = 0; i < propererList.length; i++) {
        array[i] = new Array(y);
    }


    var copy = y / propererList[0].p_enums.length;
    for (var i = 0; i < propererList.length; i++) {
        var element = propererList[i];

        var pEnums = element.p_enums;

        var yIndex = 0;

        diguiCopy(copy, pEnums, array, yIndex, i, y);


        if (i < propererList.length - 1) {
            copy = copy / propererList[i + 1].p_enums.length;
        }
    }

    // // console.log(array);
    return array;

}


function diguiCopy(copy, pEnums, array, yIndex, i, y) {

    for (var j = 0; j < pEnums.length && yIndex < y; j++) {

        //复制copy次
        for (var k = 0; k < copy; k++) {
            array[i][yIndex] = pEnums[j];
            yIndex++;
        }


    }

    //复制完判断是否复制完了
    if (yIndex < y) {
        //接着复制
        diguiCopy(copy, pEnums, array, yIndex, i, y);
    }

}


// testProduct(propererList);
function transferArrayToProperties(arr) {

    //数组长度
    let arrLength = arr.length;

    //获取每一列的枚举值
    //进行组合
    //总共的组合可能情况数量
    let zuheSize = arr[0].length;
    //最终返回的属性数组
    var propertiesArray = [];
    for (var i = 0; i < zuheSize; i++) {
        var enums = "";
        var value = "";
        for (var j = 0; j < arrLength; j++) {

            var arrLengthElementElement = arrLength[j][i];
            if (enums.indexOf(arrLengthElementElement) == -1) {
                enums += arrLengthElementElement + " ";
            }

            value = arrLengthElementElement;

            var properties = {
                "enums": enums,
                "value": value
            };

            propertiesArray.push(properties);

        }
    }

    return propertiesArray;


}

function getPropertys(specificationList){
    var propertys = [];
    for(var j=0;j<specificationList.length;j++){//整合propertys,specificationList从页面得
        var p ={
            name: specificationList[j].name,
            enums: '',
            value: '',
            type: '2'
        }
        for(var k=0;k<specificationList[j].p_enums.length;k++){
            if(k == specificationList[j].p_enums.length-1)
                p.enums += specificationList[j].p_enums[k];
            else
                p.enums += specificationList[j].p_enums[k] + ',';
        }
        propertys.push(p);//得到propertys
    }
    return propertys;
}

/**
 * 将 goodVoList 转化为 skuName -> goodVo 的字典
 * @param goodVoList
 */
function goodSkuDict(goodVoList) {
    var dict = {};
    if (goodVoList) {
        //开始循环处理
        for (var i = 0; i < goodVoList.length; i++) {
            var goodVo = goodVoList[i];
            //定义一个存放规格值的数组
            var skuValueArray = new Array();

            //开始 push 规格值
            var goodSpecVoList = goodVo.goodSpecVoList;
            for (var j = 0; j < goodSpecVoList.length; j++) {
                var goodSpecVo = goodSpecVoList[j];
                skuValueArray.push(goodSpecVo.specValue)
            }

            //将 skuValueArray 进行字典排序
            skuValueArray = skuValueArray.sort();
            //将数据存进字典
            dict[skuValueArray.join()] = goodVo;
        }
    }
    // console.log(dict)
    return dict;
}


layui.config({
    base: 'plugins/layui/modules/'
}).use(['form', 'http'], function () {
    var  form = layui.form,
        http = layui.http;
		
    // ------------------- 规格 start ----------------------
    //添加规格
    $(document).on('click', '.addSpecification', function (event) {
        if (event && event.stopPropagation) {
            event.stopPropagation();
        } else if (window.event) {
            window.event.cancelBubble = true;
        }
        $('.totalPrice').hide()
        var html = '<div class="specificationDiv">' +
            '<div class="inputList addlistf">' +
            '<div class="layui-input-inline" style="width: 85%">' +
                '<input type="text" name="sName" autocomplete="off" placeholder="请输入规格名称" class="layui-input">' +
            '</div>' +
            '<div class="layui-input-inline" style="width: 10%">' +
                '<a class="addSpecificationVal">添加规格值</a>' +
            '</div>' +
            '<i class="layui-icon layui-icon-close-fill close"></i>' +
            '</div>' +
            '<div class="inputList inputListTab">' +
            '<div class="Bigaddtab">'+
                '<div class="layui-input-inline addcheckbox">' +
                '<input type="checkbox" name="checkName" lay-skin="primary" title="" lay-filter="seletCheck">'+
                '</div>' +
                '<div class="layui-input-inline addtab">' +
                '<input type="text" name="sVal" autocomplete="off" placeholder="请输入规格值" class="layui-input"><i class="layui-icon layui-icon-close-fill close"></i>' +
                '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        $('.myMore').append(html);
        form.render();
        if($('.myMore>div').length>2){
            $('.addSpecification').hide()
        }
        var a = {
            name: '',
            p_enums: ['']
        }
        specificationList.push(a);
    })

    //添加规格值
    $(document).on('click', '.addSpecificationVal', function (event) {
        if (event && event.stopPropagation) {
            event.stopPropagation();
        } else if (window.event) {
            window.event.cancelBubble = true;
        }
        var tabhtml = 
            '<div class="Bigaddtab">'+
                '<div class="layui-input-inline addcheckbox">' +
                    '<input type="checkbox" name="checkName" lay-skin="primary" title="" lay-filter="seletCheck">'+
                '</div>' +
                '<div class="layui-input-inline addtab">' +
                    '<input type="text" name="sVal" autocomplete="off" placeholder="请输入规格值" class="layui-input"><i class="layui-icon layui-icon-close-fill close"></i>' +
                '</div>'+
            '</div>';
        var index = Number($('.addSpecificationVal').index(this));
        specificationList[index].p_enums.push('');
        $(this).parent().parent().parent().find('.inputListTab').append(tabhtml);
        form.render();
    })
    
    //删除规格 start
    $(document).on('click', '.addlistf .close', function (event) {
            if (event && event.stopPropagation) {
                event.stopPropagation();
            } else if (window.event) {
                window.event.cancelBubble = true;
            }
            var index = Number($('.addlistf .close').index(this));
            $('.specificationDiv').eq(index).remove();
        if($('.myMore>div').length<3){
            $('.addSpecification').show()
        }
        if(!$('.myMore').html()){ // 无规格
            $('.totalPrice').show()
        }
            slist();
    });
    //删除规格 end

    //删除规格项 start
    $(document).on('click', '.inputListTab .close', function (event) {
        if (event && event.stopPropagation) {
            event.stopPropagation();
        } else if (window.event) {
            window.event.cancelBubble = true;
        }
        var num = Number($('.specificationDiv').index($(this).parent().parent()
            .parent().parent()));
        if ($('.specificationDiv').eq(num).find('.Bigaddtab').length > 1) {
            var index = Number($('.Bigaddtab .close').index(this));
            $('.Bigaddtab').eq(index).remove();
        } else {
            $(this).parent().parent().parent().parent().remove();
        }
        if(!$('.myMore').html()){ // 无规格
            $('.totalPrice').show()
        }
        slist()
    });
    //删除规格项 end
    
    //更新时重新获取specificationList
    window.slist = function(){
        // depositGoodList(); //存规格信息
        specificationList = [];
        var inputList = $('.specificationDiv');
        for(var i=0;i<inputList.length;i++){
            var a = {
                name: '',
                p_enums: []
            }
            a.name = inputList.eq(i).find('input[name=sName]').val();
            var inputVal = inputList.eq(i).find('input[name=sVal]');
            var checkVal = inputList.eq(i).find('[name=checkName]');
            var checkNumber = inputList.eq(i).find('[name=checkName]:checked')
            if(checkNumber.length>0){
                for(var j=0;j<inputVal.length;j++){
                    //勾选才入明细表格
                    if(checkVal.eq(j).is(':checked')){
                        a.p_enums.push(inputVal.eq(j).val());
                    }
                }
            }else{
                a.p_enums = [''];
            }
            specificationList.push(a);
        }
        if(specificationList.length != 0){
            specificationList1 = testProduct(specificationList);//调用product.js中方法
        }
        // // console.log(specificationList)
        // // console.log(specificationList1)
        specification(specificationList1)//规格明细表格
    }
    
    //规格明细表格
    function specification(specificationList1){
        
        if(specificationList.length>0){
            
            var tableH = '<table class="layui-table inputTable"><thead><tr><th>商品编号</th>';
                                    
            for(var i=0;i<specificationList.length;i++){
                tableH += '<th>'+specificationList[i].name+'</th>'
            }
            tableH += '<th><div><span>默认商品价格</span><input type="number" name="price" autocomplete="off" class="layui-input"/></div></th>';
                        
            // 食堂等级(2020/12/5新增)
            for(var g=0;g<canteenLabelList.length;g++){
                tableH += '<th><div><span>'+canteenLabelList[g].labelName+'单价</span><input type="number" name="label'+canteenLabelList[g].id+'" autocomplete="off" class="layui-input"/></div></th>'
            }

            tableH += '</tr></thead><tbody>'
    
            for(var j=0;j<specificationList1[0].length;j++){
                tableH += '<tr><td class="my_goodNo"></td>';
                for(var k = 0;k<specificationList1.length;k++){
                    tableH += '<td>'+specificationList1[k][j]+'</td>';
                    if(k == specificationList1.length-1){
                        tableH += '<td><input type="number" name="price" autocomplete="off" class="layui-input"/></td>'
                    }        
                }
                
                // 食堂等级(2020/12/5新增)
                for(var g=0;g<canteenLabelList.length;g++){
                    tableH += '<td><input type="number" name="label'+canteenLabelList[g].id+'" autocomplete="off" class="layui-input"/></td>'
                }

                tableH += '</tr>';
            }     

            tableH += '</tbody></table>';

            $('.mytable').html(tableH)
        }else{
            $('.mytable').html('')
        }
        displayGoodList(); //更新后返值
    }

    $(document).on("input",".inputTable th input", function () {//规格明细表格中的input监听
        if($('th input[name=price]').val())
            $('td input[name=price]').val($('th input[name=price]').val());

        // 食堂等级(2020/12/5新增)
        for(var g=0;g<canteenLabelList.length;g++){
            if($('th input[name=label'+canteenLabelList[g].id+']').val())
                $('td input[name=label'+canteenLabelList[g].id+']').val($('th input[name=label'+canteenLabelList[g].id+']').val());
        }
    });
    
    //存规格信息
    // function depositGoodList(){
    // 	speciGoodList = [];
    // 	if(!specificationList1){
    // 		return
    // 	}
        // for(var x=0;x<specificationList1[0].length;x++){
        // 	var pp = {
        // 		"goodNo": $('.my_goodNo').eq(x).html(),
        // 		"price": $('.inputTable td input[name=price]').eq(x).val(),
        // 		"stockCount": 99999,
        // 		"goodSpecParamsList":[]                    //商品的规格
        // 	};
        // 	for(var y=0;y<specificationList1.length;y++){
        // 		pp.goodSpecParamsList.push(specificationList1[y][x]);
        // 	}
        // 	speciGoodList.push(pp)
        // }
        // // console.log(speciGoodList)
    // }
    
    //回显已有规格信息
    function displayGoodList(){
        var num = 0;
        $('.inputTable th').each(function(i){
            num++;				  
        });
        num = num - 1 - canteenLabelList.length;
        $('.inputTable tr').each(function(i){        // 遍历 tr
            var arr = [];
            $(this).children('td').each(function(j){  // 遍历 tr 的各个 td
                if(j!=0&&j<num){
                    arr.push($(this).text());
                }
            });
            // var valList = getVal(arr);
            var preList = getValPre(arr)
            // // console.log(valList)
            // console.log(preList)
            if(preList){
                var tdlength = $(this).children('td').length;               
                $(this).children('td').each(function(j){                    // 遍历 tr 的各个 td 回显规格详情
                    if(j == 0){
                        $(this).html(preList.goodNo);        // 编号
                    }
                    $(this).find("input[name=price]").val(preList.price);        // 默认商品价格

                    // 食堂等级价格(2020/12/5新增)
                    
                    var list = labelInfoWith(canteenLabelList, preList.goodLabelPriceList) // 食堂等级列表对应价格(2020/12/8新增)
                    // console.log(list)
                    for(var s=0;s<list.length;s++){
                        $(this).find('input[name=label'+list[s].id+']').val(list[s].goodPrice?list[s].goodPrice:preList.price)
                    }
                });
            }
        });
    }
    
    //比对获取值
    // function getVal(arr){
    // 	var list = '';
    // 	$.each(speciGoodList, function(index,data) {
    // 		if(JSON.stringify(arr) == JSON.stringify(data.goodSpecParamsList)){
    // 			list = data;
    // 			return false	
    // 		}
    // 	});
    // 	return list;
    // }
    function getValPre(arr){
        var list = '';
        // // console.log(arr)
        // // console.log(prespeciGoodList)
        $.each(prespeciGoodList, function(index,data) {
            // // console.log(arr.toString())
            // // console.log(data.goodSpecParamsList.toString())
            if(arr.toString() == data.goodSpecParamsList.toString()){
                list = data;
                return false	
            }
        });
        return list;
    }
    
    //监听input
    $(document).on("input",".typeSpecification input", function () {
        var flag = false
        if($(this).attr('name')=='sName'){
            var sindex = $(this).parent().parent().parent().index()
            // console.log(sindex)
            for(var i=0;i<specificationList.length;i++){
                if($.trim($(this).val())){
                    if($(this).val() == specificationList[i].name && sindex != i){
                        layer.msg('规格名称【'+$(this).val()+'】重复')
                        flag = true
                        break
                    }
                }else{
                    break
                }
            }
            setTimeout(function(){
                if(!flag){
                    slist()//获取specificationList
                }
            
            },800)
        }else if($(this).attr('name')=='sVal'){
            var mylong = $(this).parent().parent().find('[name="checkName"]:checked').length;
            if(mylong>0){
                var num = $(this).parent().parent().parent().parent().index()
                // num = num - 1
                var sindex = $(this).parent().parent().index()
                for(var i=0;i<specificationList[num].p_enums.length;i++){
                    if($.trim($(this).val())){
                        if($(this).val() && $(this).val() == specificationList[num].p_enums[i] && sindex != i){
                            // console.log(specificationList[num].p_enums[i])
                            layer.msg('规格值【'+$(this).val()+'】重复')
                            flag = true
                            break
                        }
                    }else{
                        break
                    }
                }
                setTimeout(function(){
                    if(!flag){
                        slist()//获取specificationList
                    }
                },800)
            }
        }
        
    });
    
    //监听复选框
    form.on('checkbox(seletCheck)', function(data){
        if(data.elem.checked){
            var flag = false
            var num = $(this).parent().parent().parent().parent().index()
            // num = num - 1
            var myVal = $(this).parent().parent().find('input[name=sVal]').val();
            // console.log(myVal);
            for(var i=0;i<specificationList[num].p_enums.length;i++){
            if(myVal && myVal == specificationList[num].p_enums[i]){
                layer.msg('规格值【'+myVal+'】重复')
                flag = true
                break
            }
            } 
            slist()//获取specificationList
        }else{
            slist()//获取specificationList
        } 
    }); 
    // ------------------- 规格 end ----------------------

    // 刷新表格明细
    $(document).on('click', '.reFrashBtn', function() {
        slist()
    })

})
